<?php
/**
 * 登录管理
 * 作者：MYL
 */
namespace app\api\controller;

use app\api\model\UserModel;
use think\Controller;
use lib\sendAPI;
use think\Db;

class Admin extends Controller
{
    /**
     * 判断是否在微信端登录
     */
    public function isWeChat()
    {
        $useragent = $_SERVER['HTTP_USER_AGENT'];
        if(strpos($useragent, 'MicroMessenger') === false && strpos($useragent, 'Windows Phone') === false ){
            ajaxReturn(['status' => -1, 'msg' => '非微信浏览器禁止访问，请在微信打开！']);
        } else {
            ajaxReturn(['status' => 1, 'msg' => '微信浏览器允许访问']);
        }
    }

    /**
     * 用户登录
     */
    public function Login()
    {
        if ($this->request->isPost()) {
            if (!empty($_POST['mobile']) && $_POST['password'] ) {
                $map['mobile'] = $_POST['mobile'];
                $map['password'] = encrypt($_POST['password']);
                $result          = DB::name('users')->field("*,mobile,FROM_UNIXTIME(reg_time,'%Y-%m-%d %H:%i:%s')as regTime")->where($map)->find();
                if ($result) {
                    if ($result['is_lock']==1) {
                        ajaxReturn(['status' => -1, 'msg' => '您的账号已被冻结，请联系管理员！！！']);
                    } else {
                        session('user_id',$result['user_id']);
                        ajaxReturn(['status' => 1, 'msg' => 'Success！', 'result' => $result]);
                    }
                } else {
                    ajaxReturn(['status' => -1, 'msg' => '登录失败，账号或密码错误，请重新登陆！', 'result' => []]);
                }
            }
        }

    }

    /**
     * 游客记录
     */
    public function tourist()
    {
        $data['name'] = I('post.name');
        $data['mobile'] = I('post.mobile');
        $data['add_time'] = time();

        if ($data['name']=='') {
            ajaxReturn(['status' => -1, 'msg' => '姓名不能为空!']);
        }
        if ($data['mobile']=='') {
            ajaxReturn(['status' => -1, 'msg' => '手机号不能为空!']);
        }
        $rs = M('tourist')->where("mobile",$data['mobile'])->find();
        if (!empty($rs)) {
            ajaxReturn(['status' => -1, 'msg' => '此手机号已经提交，请更换手机号！']);
        }
        $row = M('tourist')->insertGetId($data);
        if (!empty($row)) {
            ajaxReturn(['status' => 1, 'msg' => 'Success!', 'Id' => $row]);
        } else {
            ajaxReturn(['status' => -1, 'msg' => 'Error!']);
        }
    }

    /**
     * 商品2级导航和3级
     */
    public function all_category_two()
    {
        $all_category = M('goods_category')->field('id,name,image')->where("level=2 and is_show=1")->select();
        foreach ($all_category as $key => $val) {
            $second_level = M('goods_category')->field('id,name')->where(["parent_id" => $val['id']])->select();
            $all_category[$key]['son'] = $second_level;
        }
        if (!empty($all_category)) {
            ajaxReturn(['status' => 1, 'msg' => '获取成功！', 'result' => $all_category]);
        } else {
            ajaxReturn(['status' => -1, 'msg' => '获取失败！', 'result' => []]);
        }
    }

    /**
     * 游客发布需求
     */
    public function demand()
    {
        $userId = I('post.userId'); //用户ID
        $touristId = I('post.touristId'); //游客ID

        $data['first_level'] = I('post.first_level'); //一级分类
        $data['second_level'] = I('post.second_level'); //二级分类
        $data['content'] = I('post.content'); //内容
        $data['price'] = I('post.price'); //价格

        if (empty($userId)){
            $data['status'] = '2'; //状态 1.会员 2.游客
            $row = M('tourist')->where('id',$touristId)->update($data);
            if (!empty($row)) {
                ajaxReturn(['status' => 1, 'msg' => 'Success!']);
            } else {
                ajaxReturn(['status' => -1, 'msg' => 'Error!']);
            }
        } else {
            $data['status'] = '1';
            $user = Db::name('users')->field('nickname,mobile')->where('user_id',$userId)->find();
            $data['name'] = $user['nickname'];
            $data['mobile'] = $user['mobile'];
            $data['add_time'] = time();
            $row = M('tourist')->insert($data);
            if (!empty($row)) {
                ajaxReturn(['status' => 1, 'msg' => 'Success!']);
            } else {
                ajaxReturn(['status' => -1, 'msg' => 'Error!']);
            }
        }
    }

    /**
     * 用户注册
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function register()
    {
        ajaxReturn(['status' => '666', 'msg' => '该接口已暂停服务，请联系管理员！']);
        if ($this->request->isPost()) {
            $map['is_enterprise'] = I('post.is_enterprise'); //注册类型 1.企业 2.个人
            $map['nickname'] = I('post.nickname'); //用户名称
            $map['password'] = encrypt(I('post.password')); //用户密码
            $map['email'] = I('post.email'); //用户邮箱
            $map['mobile'] = I('post.mobile'); //用户电话
            $map['reg_time'] = time();
            $code  = I('post.code');

            //判断该手机号是否已注册
            if ($code=='' && $map['mobile']=='') {
                ajaxReturn(['status' => -1, 'msg' => '手机号码或验证码为空，请重新输入！']);
            }
            $result = M('users')->field('user_id')->where('mobile',$map['mobile'])->find();
            if ($result) {
                ajaxReturn(['status' => -1, 'msg' => '此手机号已经注册，请更换手机号注册！']);
            }
            $mobile = session('mobile'); $codes = session('code'); //从session中取回验证码和手机号
            if (!($mobile == $map['mobile'])) {
                ajaxReturn(['status' => -1, 'msg' => '手机号码错误，请重新输入！']);
            }
            if (!($code == $codes)) {
                ajaxReturn(['status' => -1, 'msg' => '验证码错误，请重新输入或重新获取！']);
            }
            session('mobile', null);
            session('code', null); // 清除session
            $user = UserModel::increase($map);
            if ($user) {
                ajaxReturn(['status' => 1, 'msg' => 'Success！']);
            } else {
                ajaxReturn(['status' => -1, 'msg' => '注册失败，请重新注册！']);
            }
        } else {
            ajaxReturn(['status' => -1, 'msg' => '请填写数据！']);
        }
    }

    /**
     * 忘记密码
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function forget()
    {
        if ($this->request->isPost()) {
            $password = encrypt(I('post.password'));
            $mobile = I('post.mobile');
            $code  = I('post.code');

            if ($code=='' && $mobile=='') {
                ajaxReturn(['status' => -1, 'msg' => '手机号码或验证码为空，请重新输入！']);
            }
            $mobile = session('mobile'); $codes = session('code'); //从session中取回验证码和手机号
            if (!($mobile == $mobile)) {
                ajaxReturn(['status' => -1, 'msg' => '手机号码错误，请重新输入！']);
            }
            if (!($code == $codes)) {
                ajaxReturn(['status' => -1, 'msg' => '验证码错误，请重新输入或重新获取！']);
            }
            session('mobile', null);
            session('code', null); // 清除session
            //判断新密码和旧密码是否一致
            $mi['mobile'] = $mobile;
            $mi['password'] = $password;
            $mima = UserModel::whereGetOne($mi);
            if (!empty($mima)) {
                ajaxReturn(['status' => -1, 'msg' => '修改失败，新密码和旧密码不能一样！']);
            }
            //修改密码
            $data = array();
            $where['mobile'] = $mobile;
            $data['password'] = $password;
            $user = UserModel::modify($where,$data);
            if ($user) {
                ajaxReturn(['status' => 1, 'msg' => 'Success！']);
            } else {
                ajaxReturn(['status' => -1, 'msg' => '没有此账号，请注册！']);
            }
        } else {
            ajaxReturn(['status' => -1, 'msg' => '请填写数据！']);
        }
    }

    /**
     * 获取手机短信验证码
     * @return \think\response\Json
     */
    public function sendsms()
    {
        if ($this->request->isPost()) {
            $mobile = $_POST['mobile'];
            //检测是手机号的格式
            if (!check_mobile($mobile)) {
                ajaxReturn(['status' => -1, 'msg' => '手机号码格式错误！']);
            }
            $rs = M('users')->field('user_id')->where('mobile',$mobile)->find();
            if (empty($rs)) {
                ajaxReturn(['status' => -1, 'msg' => '发送失败，该手机号码未注册！']);
            }
            $rand_string = randString();
            $url = "http://www.ztsms.cn/sendNSms.do";//提交地址
            $username = 'b15902185331';//用户名
            $password = 'xH5jHoly';//原密码
            $sendAPI = new sendAPI($url, $username, $password);

            if (check_mobile($mobile)) {
                $data = array(
                    'content' => "您的验证码是$rand_string.【Vip系统】",//短信内容
                    'mobile' => $mobile,//手机号码
                    'productid' => '676767',//产品id
                    'xh' => ''//小号
                );
                $sendAPI->data = $data;//初始化数据包
                $return = $sendAPI->sendSMS('POST');//GET or POST
                $return = substr($return, 0, 1);
            }
            if ($return == '1') {
                //添加进缓存
                session('mobile', $mobile);
                session('code', $rand_string);
                $json['msg'] = '短信发送成功';
                $json['status'] = $return;
            } elseif ($return == -1) {
                $json['msg'] = '短信发送失败，请重试！';
                $json['status'] = $return;
            }
            ajaxReturn($json);
        }
    }

    //注销退出
    public function logout(){
        session('user_id',null);
        header('Location: http://vip.bndvip.com/html/login.html');
    }

}